package Simulator;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

@SuppressWarnings("serial")
public class GenerationView extends JFrame implements SimulatorViewInterface {
	private static final Color EMPTY_COLOR = Color.white;
	private final String STEP_PREFIX = "Step: ";
	private JLabel stepLabel;
	private FieldView fieldView;
	// A statistics object computing and storing simulation information
	private FieldStats stats;

	public GenerationView(int height, int width) {
		stats = new FieldStats();

		setTitle("Fox and Rabbit Simulation");
		ImageIcon icon = new ImageIcon("src\\media\\konijn.gif");
		setIconImage(icon.getImage());
		stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);

		setLocation(0, 175);
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

		fieldView = new FieldView(height, width);
		fieldView.setColor(Rabbit.class, Color.orange);
		fieldView.setColor(Fox.class, Color.red);
		fieldView.setColor(Hunter.class, Color.green);
		fieldView.setColor(Bird.class, Color.blue);

		Container contents = getContentPane();
		contents.add(stepLabel, BorderLayout.NORTH);
		contents.add(fieldView, BorderLayout.CENTER);

		setFieldSize(height, width);
		setVisible(true);
	}

	public void setFieldSize(int height, int width) {
		fieldView.setSize(height, width);
		setSize(fieldView.getPreferredSize());
		pack();
	}

	public void showStatus(int step, Field field) {
		stepLabel.setText(STEP_PREFIX + step);
		stats.reset();

		fieldView.preparePaint();

		for (int row = 0; row < field.getDepth(); row++) {
			for (int col = 0; col < field.getWidth(); col++) {
				ActorInterface actor = field.getActorAt(row, col);
				if (actor != null) {
					stats.incrementCount(actor.getClass());
					fieldView.drawMark(col, row,
							fieldView.getColor(actor.getClass()));
				} else {
					fieldView.drawMark(col, row, EMPTY_COLOR);
				}
			}
		}
		stats.countFinished();

		fieldView.repaint();
	}

	public boolean isViable(Field field) {
		return stats.isViable(field);
	}
}
